<template>
  <div class="inspection-form-container">
    <!-- 操作栏（新增导出按钮） -->
    <div class="operation-bar">
      <!-- 新建按钮（权限控制） -->
      <el-button 
        type="primary" 
        @click="openCreateDialog"
        v-if="hasPermission('Add')"
      >
        <i class="el-icon-plus"></i> 新建
      </el-button>
      <!-- 导出按钮（权限控制） -->
      <el-button 
        type="info" 
        @click="exportExcel"
        v-if="hasPermission('Export')"
        style="margin-left: 10px"
      >
        <i class="el-icon-download"></i> 导出Excel
      </el-button>
      <!-- 搜索区域 -->
      <el-input
        v-model="searchKeyword"
        placeholder="请输入查询的检验人员"
        clearable
        style="width: 300px; margin-left: 20px"
        @keyup.enter="handleSearch"
      ></el-input>
      <el-button type="success" @click="handleSearch" style="margin-left: 10px">
        <i class="el-icon-search"></i> 查询
      </el-button>
      
      <!-- 权限状态提示（实际项目中可移除） -->
      <div class="permission-info" v-if="showPermissionInfo">
        当前权限: 
        <span :class="{ 'permission-enabled': hasPermission('Add') }">新建</span> |
        <span :class="{ 'permission-enabled': hasPermission('Update') }">编辑</span> |
        <span :class="{ 'permission-enabled': hasPermission('Delete') }">删除</span> |
        <span :class="{ 'permission-enabled': hasPermission('Export') }">导出</span>
      </div>
    </div>

    <!-- 表格展示 -->
    <el-table
      :data="filteredData"
      border
      stripe
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column prop="id" label="序号" width="80" align="center"></el-table-column>
      <el-table-column label="工单号" prop="workOrderNo" align="center"></el-table-column>
      <el-table-column label="产品代码" prop="productCode" align="center"></el-table-column>
      <el-table-column label="批次号" prop="batchNo" align="center"></el-table-column>
      <el-table-column label="时间段" align="center">
        <template #default="scope">
          {{ scope.row.startTime }} - {{ scope.row.endTime }}
        </template>
      </el-table-column>
      <el-table-column label="检验员" align="center">
        <template #default="scope">
          {{ scope.row.inspectors.join('、') }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template #default="scope">
          <el-tag :type="statusTagType[scope.row.status]">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="quantity" label="数量" align="center"></el-table-column>
      <el-table-column prop="totalTime" label="总时长(小时)" align="center"></el-table-column>
      <el-table-column label="操作" width="160" align="center">
        <template #default="scope">
          <!-- 编辑按钮（权限控制） -->
          <el-button
            type="warning"
            size="mini"
            @click="openEditDialog(scope.row)"
            v-if="hasPermission('Update')"
          >
            <i class="el-icon-edit"></i> 编辑
          </el-button>
          <!-- 删除按钮（权限控制） -->
          <el-button
            type="danger"
            size="mini"
            @click="handleDelete(scope.row.id)"
            style="margin-left: 5px"
            v-if="hasPermission('Delete')"
          >
            <i class="el-icon-delete"></i> 删除
          </el-button>
          <!-- 无权限时显示占位符 -->
          <span v-if="!hasPermission('Update') && !hasPermission('Delete')">-</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新建/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="90%"
      :before-close="handleDialogClose"
      ref="dialogRef"
    >
      <div class="dialog-content">
        <!-- 上部分：基本信息 -->
        <div class="dialog-section">
          <h3 class="section-title">基本信息</h3>
          <div class="form-group">
            <el-input
              v-model="baseInfo.workOrderNo"
              placeholder="工单号"
              style="width: 16%; margin-right: 0.5%"
              @keyup.enter="handleWorkOrderEnter"
            ></el-input>
            <el-input
              v-model="baseInfo.productCode"
              placeholder="产品代码"
              style="width: 16%; margin-right: 0.5%"
            ></el-input>
            <el-input
              v-model="baseInfo.batchNo"
              placeholder="批次号"
              style="width: 16%; margin-right: 0.5%"
            ></el-input>
            <el-input
              v-model="baseInfo.productSpec"
              placeholder="产品规格"
              style="width: 16%; margin-right: 0.5%"
            ></el-input>
            <el-input
              v-model="baseInfo.grade"
              placeholder="牌号"
              style="width: 16%; margin-right: 0.5%"
            ></el-input>
            <el-input
              v-model="baseInfo.coating"
              placeholder="镀层"
              style="width: 16%;"
            ></el-input>
          </div>
          <div class="form-group">
            <el-input
              v-model.number="baseInfo.unitWeight"
              type="number"
              placeholder="单重"
              min="0"
              style="width: 19%; margin-right: 1%"
            ></el-input>
            <el-input
              v-model.number="baseInfo.batchQuantity"
              type="number"
              placeholder="批次数量"
              min="0"
              style="width: 19%; margin-right: 1%"
            ></el-input>
            <el-input
              v-model.number="baseInfo.qualifiedQuantity"
              type="number"
              placeholder="合格数量"
              min="0"
              style="width: 19%; margin-right: 1%"
            ></el-input>
            <el-input
              v-model.number="baseInfo.batchWeight"
              type="number"
              placeholder="批次重量"
              min="0"
              style="width: 19%; margin-right: 1%"
            ></el-input>
            <el-input
              v-model.number="baseInfo.packagingWeight"
              type="number"
              placeholder="包材总重"
              min="0"
              style="width: 19%;"
            ></el-input>
          </div>
        </div>
        
        <!-- 下部分：检验记录 -->
        <div class="dialog-section">
          <h3 class="section-title">检验记录</h3>
          <div
            v-for="(row, index) in formRows"
            :key="index"
            class="form-row"
          >
            <!-- 开始日期和时间 -->
            <div style="display: inline-flex; width: 25%;">
              <el-date-picker
                v-model="row.startDate"
                type="date"
                placeholder="开始日期"
                style="width: 48%;"
                :clearable="false"
                @change="calculateTimeDiff(row)"
              ></el-date-picker>
              <el-time-picker
                v-model="row.startTime"
                placeholder="开始时间"
                style="width: 48%; margin-left: 4%;"
                :clearable="false"
                @change="calculateTimeDiff(row)"
              ></el-time-picker>
            </div>
            <!-- 结束日期和时间 -->
            <div style="display: inline-flex; width: 25%; margin-left: 10px;">
              <el-date-picker
                v-model="row.endDate"
                type="date"
                placeholder="结束日期"
                style="width: 48%;"
                :clearable="false"
                @change="calculateTimeDiff(row)"
              ></el-date-picker>
              <el-time-picker
                v-model="row.endTime"
                placeholder="结束时间"
                style="width: 48%; margin-left: 4%;"
                :clearable="false"
                @change="calculateTimeDiff(row)"
              ></el-time-picker>
            </div>
            <el-select
              v-model="row.inspectors"
              multiple
              placeholder="请选择检验员"
              style="width: 15%; margin-left: 10px"
            >
              <el-option
                v-for="item in inspectorOptions"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
            <el-select
              v-model="row.status"
              placeholder="请选择状态"
              style="width: 8%; margin-left: 10px"
            >
              <el-option
                v-for="item in statusOptions"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
            <el-input
              v-model.number="row.quantity"
              type="number"
              placeholder="数量"
              min="0"
              style="width: 8%; margin-left: 10px"
            ></el-input>
            <!-- 总时间文本框 -->
            <el-input
              v-model="row.totalTime"
              placeholder="总时间(小时)"
              style="width: 8%; margin-left: 10px"
              readonly
              :disabled="true"
            ></el-input>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeRow(index)"
              :disabled="formRows.length <= 1 || !hasPermission('Update')"
              style="margin-left: 10px"
            >删除</el-button>
          </div>
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="addRow"
            style="margin-top: 10px"
            v-if="hasPermission('Update')"
          >
            增加一行
          </el-button>
        </div>
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" v-if="hasPermission(currentEditId ? 'Update' : 'Add')">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
// 导入Excel导出依赖
import XLSX from 'xlsx';
import FileSaver from 'file-saver';

export default {
  data() {
    return {
      tableData: [
        {
          id: 1,
          workOrderNo: 'WO202307001',
          productCode: 'PC001',
          batchNo: 'B202307001',
          productSpec: 'Φ10×20mm',
          grade: '304',
          coating: 'Zn',
          unitWeight: 0.5,
          batchQuantity: 1000,
          qualifiedQuantity: 980,
          batchWeight: 500,
          packagingWeight: 50,
          startTime: '2023-07-01 08:00',
          endTime: '2023-07-01 12:00',
          inspectors: ['张三', '李四'],
          status: '已完成',
          quantity: 25,
          totalTime: '4.00'
        },
        {
          id: 2,
          workOrderNo: 'WO202307002',
          productCode: 'PC002',
          batchNo: 'B202307002',
          productSpec: 'Φ12×25mm',
          grade: '316',
          coating: 'Ni',
          unitWeight: 0.8,
          batchQuantity: 800,
          qualifiedQuantity: 790,
          batchWeight: 640,
          packagingWeight: 60,
          startTime: '2023-07-01 13:00',
          endTime: '2023-07-01 17:00',
          inspectors: ['王五'],
          status: '待处理',
          quantity: 18,
          totalTime: '4.00'
        }
      ],
      searchKeyword: '',
      dialogVisible: false,
      dialogTitle: '新建记录',
      currentEditId: null,
      PermissionAll: [], // 权限数组（从store获取）
      // 基本信息部分
      baseInfo: {
        workOrderNo: '',
        productCode: '',
        batchNo: '',
        productSpec: '',
        grade: '',
        coating: '',
        unitWeight: null,
        batchQuantity: null,
        qualifiedQuantity: null,
        batchWeight: null,
        packagingWeight: null
      },
      // 检验记录部分
      formRows: [
        {
          startDate: null,
          startTime: null,
          endDate: null,
          endTime: null,
          inspectors: [],
          status: '',
          quantity: null,
          totalTime: ''
        }
      ],
      inspectorOptions: ['张三', '李四', '王五', '赵六'],
      statusOptions: ['待处理', '处理中', '已完成', '已取消'],
      statusTagType: {
        '待处理': 'info',
        '处理中': 'warning',
        '已完成': 'success',
        '已取消': 'danger'
      },
      showPermissionInfo: true
    };
  },
  computed: {
    filteredData() {
      if (!this.searchKeyword) return this.tableData;
      
      const keyword = this.searchKeyword.toLowerCase();
      return this.tableData.filter(item => {
        const baseInfoMatch = item.workOrderNo.toLowerCase().includes(keyword) ||
                             item.productCode.toLowerCase().includes(keyword) ||
                             item.batchNo.toLowerCase().includes(keyword) ||
                             item.productSpec.toLowerCase().includes(keyword) ||
                             item.grade.toLowerCase().includes(keyword) ||
                             item.coating.toLowerCase().includes(keyword);
                             
        const timeMatch = item.startTime.toLowerCase().includes(keyword) || 
                         item.endTime.toLowerCase().includes(keyword);
                         
        const inspectorMatch = item.inspectors.some(ins => 
          ins.toLowerCase().includes(keyword)
        );
        
        const statusMatch = item.status.toLowerCase().includes(keyword);
        const quantityMatch = item.quantity.toString().includes(keyword);
        
        return baseInfoMatch || timeMatch || inspectorMatch || statusMatch || quantityMatch;
      });
    }
  },
  methods: {
    // 导出Excel核心方法
    exportExcel() {
      const inspectorKeyword = this.searchKeyword.trim();
      if (!inspectorKeyword) {
        this.$message.warning('请先输入要查询的检验人员');
        return;
      }

      // 过滤该检验人员涉及的记录（不区分大小写）
      const lowerKeyword = inspectorKeyword.toLowerCase();
      const exportData = this.tableData.filter(item => 
        item.inspectors.some(ins => ins.toLowerCase().includes(lowerKeyword))
      );

      if (exportData.length === 0) {
        this.$message.info(`未找到检验人员"${inspectorKeyword}"相关的记录`);
        return;
      }

      // 整理导出数据（仅保留需要的列）
      const excelData = exportData.map(item => ({
        '工单号': item.workOrderNo,
        '产品代码': item.productCode,
        '开始时间': item.startTime,
        '结束时间': item.endTime,
        '总时长(小时)': item.totalTime,
        '数量': item.quantity
      }));

      // 生成Excel工作簿
      const ws = XLSX.utils.json_to_sheet(excelData);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, `检验人员${inspectorKeyword}记录`);

      // 导出文件
      const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
      const excelBlob = new Blob([excelBuffer], { type: 'application/octet-stream' });
      FileSaver.saveAs(excelBlob, `检验人员${inspectorKeyword}_记录_${new Date().toLocaleDateString()}.xlsx`);
    },

    get_gx_detail_all() {
      console.log("获取工序和检验员数据");
      this.inspectorOptions = [];
      this.statusOptions = [];
      // 实际项目确保this.http已挂载（axios）
      this.http.get('api/ak_wgjy_sgd_peizhi/search_gx_detail', {})
        .then((reslut) => {
          console.log("工序/检验员数据:", reslut);
          reslut.rows.forEach(per_ => {
            if (per_.type === "工序") {
              this.statusOptions.push(per_.name);
            } else {
              this.inspectorOptions.push(per_.name);
            }
          });
        })
        .catch((error) => {
          console.error('同步工序/检验员失败:', error);
        });

      // 获取表格数据
      this.tableData = [];
      this.http.get('api/ak_wgjy_sgd_peizhi/search_info_db', {})
        .then((reslut) => {
          console.log("表格数据:", reslut);
          reslut.rows.forEach((per_, index) => {
            per_.id = index + 1;
            per_.inspectors = per_.inspectors ? per_.inspectors.split(', ') : [];
            this.tableData.push(per_);
          });
        })
        .catch((error) => {
          console.error('同步表格数据失败:', error);
        });
    },

    handleWorkOrderEnter() {
      console.log('工单号回车:', this.baseInfo.workOrderNo);
      this.$message.info('检测到工单号回车，同步生产任务');
      this.http.get('api/table_wgjy/SyncProductionTask_wgjy_get', {
        name_order: this.baseInfo.workOrderNo
      })
        .then((reslut) => {
          console.log("生产任务数据:", reslut);
          const task = reslut.rows[0] || {};
          this.baseInfo.productCode = task.product || '';
          this.baseInfo.batchNo = task.raw_lot_id || '';
          this.baseInfo.productSpec = task.prodcut_spec || '';
          this.baseInfo.grade = task.grade || '';
          this.baseInfo.unitWeight = task.piece_weight || null;
        })
        .catch((error) => {
          console.error('同步生产任务失败:', error);
        });
    },

    // 权限检查核心方法：判断PermissionAll是否包含目标权限
    hasPermission(permission) {
      // 容错：PermissionAll未初始化时返回false
      if (!Array.isArray(this.PermissionAll)) return false;
      // 权限标识需与后端一致（如"Add"、"Update"、"delete"、"export"）
      return this.PermissionAll.includes(permission);
    },

    openCreateDialog() {
      if (!this.hasPermission('Add')) {
        this.$message.error('您没有新建权限，请联系管理员');
        return;
      }
      this.dialogTitle = '新建记录';
      this.currentEditId = null;
      this.resetFormData();
      this.$nextTick(() => {
        this.dialogVisible = true;
      });
    },

    openEditDialog(row) {
      if (!this.hasPermission('Update')) {
        this.$message.error('您没有编辑权限，请联系管理员');
        return;
      }
      this.dialogTitle = '编辑记录';
      this.currentEditId = row.id;
      this.resetFormData();

      // 填充基本信息
      this.baseInfo = {
        workOrderNo: row.workOrderNo || '',
        productCode: row.productCode || '',
        batchNo: row.batchNo || '',
        productSpec: row.productSpec || '',
        grade: row.grade || '',
        coating: row.coating || '',
        unitWeight: row.unitWeight || null,
        batchQuantity: row.batchQuantity || null,
        qualifiedQuantity: row.qualifiedQuantity || null,
        batchWeight: row.batchWeight || null,
        packagingWeight: row.packagingWeight || null
      };

      // 解析时间为日期和时间组件
      const startDateTime = row.startTime ? new Date(row.startTime) : new Date();
      const endDateTime = row.endTime ? new Date(row.endTime) : new Date();
      this.formRows[0] = {
        startDate: new Date(startDateTime.getFullYear(), startDateTime.getMonth(), startDateTime.getDate()),
        startTime: new Date(startDateTime),
        endDate: new Date(endDateTime.getFullYear(), endDateTime.getMonth(), endDateTime.getDate()),
        endTime: new Date(endDateTime),
        inspectors: [...(row.inspectors || [])],
        status: row.status || '',
        quantity: row.quantity || null,
        totalTime: row.totalTime || ''
      };

      this.$nextTick(() => {
        this.calculateTimeDiff(this.formRows[0]);
        this.dialogVisible = true;
      });
    },

    resetFormData() {
      // 重置基本信息
      this.baseInfo = {
        workOrderNo: '',
        productCode: '',
        batchNo: '',
        productSpec: '',
        grade: '',
        coating: '',
        unitWeight: null,
        batchQuantity: null,
        qualifiedQuantity: null,
        batchWeight: null,
        packagingWeight: null
      };

      // 重置检验记录（默认当天日期和时间）
      const today = new Date();
      const defaultDate = new Date(today.getFullYear(), today.getMonth(), today.getDate());
      this.formRows = [
        {
          startDate: defaultDate,
          startTime: new Date(today.getFullYear(), today.getMonth(), today.getDate(), 8, 0, 0),
          endDate: defaultDate,
          endTime: new Date(today.getFullYear(), today.getMonth(), today.getDate(), 12, 0, 0),
          inspectors: [],
          status: '',
          quantity: null,
          totalTime: ''
        }
      ];

      // 计算初始总时间
      this.$nextTick(() => {
        this.calculateTimeDiff(this.formRows[0]);
      });
    },

    addRow() {
      if (!this.hasPermission('Update')) {
        this.$message.error('您没有编辑权限，无法添加行');
        return;
      }
      const today = new Date();
      const defaultDate = new Date(today.getFullYear(), today.getMonth(), today.getDate());
      const newRow = {
        startDate: defaultDate,
        startTime: new Date(today.getFullYear(), today.getMonth(), today.getDate(), 8, 0, 0),
        endDate: defaultDate,
        endTime: new Date(today.getFullYear(), today.getMonth(), today.getDate(), 12, 0, 0),
        inspectors: [],
        status: '',
        quantity: null,
        totalTime: ''
      };
      this.formRows.push(newRow);
      this.$nextTick(() => {
        this.calculateTimeDiff(newRow);
      });
    },

    removeRow(index) {
      if (!this.hasPermission('Update')) {
        this.$message.error('您没有编辑权限，无法删除行');
        return;
      }
      if (this.formRows.length <= 1) {
        this.$message.warning('至少保留一行检验记录');
        return;
      }
      this.formRows.splice(index, 1);
    },

    handleSearch() {
      console.log('搜索关键词:', this.searchKeyword);
    },

    handleDelete(id) {
      if (!this.hasPermission('Delete')) {
        this.$message.error('您没有删除权限，请联系管理员');
        return;
      }
      this.$confirm('确定要删除这条记录吗？删除后不可恢复！', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.tableData = this.tableData.filter(item => item.id !== id);
          this.$message.success('删除成功');
          // 实际项目需调用后端删除接口
          // this.http.post('api/delete', {id}).then(res => {/* 后端删除逻辑 */});
        })
        .catch(() => {
          this.$message.info('已取消删除');
        });
    },

    submitForm() {
      // 权限校验
      const requiredPerm = this.currentEditId ? 'Update' : 'Add';
      if (!this.hasPermission(requiredPerm)) {
        this.$message.error(`您没有${this.currentEditId ? '编辑' : '新建'}权限，请联系管理员`);
        return;
      }

      if (!this.validateForm()) {
        return;
      }

      if (this.currentEditId) {
        // 编辑操作
        const index = this.tableData.findIndex(item => item.id === this.currentEditId);
        if (index !== -1) {
          const row = this.formRows[0];
          this.tableData[index] = {
            ...this.tableData[index],
            ...this.baseInfo,
            startTime: this.formatDateTime(row.startDate, row.startTime),
            endTime: this.formatDateTime(row.endDate, row.endTime),
            inspectors: row.inspectors,
            status: row.status,
            quantity: row.quantity,
            totalTime: row.totalTime
          };
          // this.updateWorkOrder(this.tableData[index], "编辑");
          this.$message.success('编辑成功');
        }
      } else {
        // 新建操作
        const inBefore = this.tableData.length;
        this.formRows.forEach(row => {
          const newId = Math.max(...this.tableData.map(item => item.id), 0) + 1;
          const newRecord = {
            id: newId,
            ...this.baseInfo,
            startTime: this.formatDateTime(row.startDate, row.startTime),
            endTime: this.formatDateTime(row.endDate, row.endTime),
            inspectors: row.inspectors,
            status: row.status,
            quantity: row.quantity,
            totalTime: row.totalTime
          };
          this.tableData.push(newRecord);
        });
        const inAfter = this.tableData.length;
        const newRecords = this.tableData.slice(inBefore, inAfter);
        this.updateWorkOrder(newRecords, "创建");
        this.$message.success('创建成功');
      }
      this.dialogVisible = false;
    },

    updateWorkOrder(workOrder, option) {
      try {
        console.log(`${option}工单数据:`, workOrder);
        const jsonStringMesData = JSON.stringify(workOrder);
        const loadingInstance = this.$loading({
          lock: true,
          text: `提交${option}申请中...`,
          spinner: 'el-icon-loading',
          background: 'rgba(247, 237, 237, 0.7)'
        });

        this.http.get('api/ak_wgjy_sgd_peizhi/insert_info_gx', {
          option: option,
          mes_data: jsonStringMesData
        })
          .then((reslut) => {
            loadingInstance.close();
            if (reslut === "成功") {
              this.$message.success(`工单${option}成功`);
            } else {
              this.$message.warning(`工单${option}返回异常: ${reslut}`);
            }
          })
          .catch((error) => {
            console.error(`${option}工单失败:`, error);
            loadingInstance.close();
            this.$message.error(`工单${option}失败，请重试`);
          });
      } catch (error) {
        console.error(`${option}工单异常:`, error);
        this.$message.error(`工单${option}失败，请稍后重试`);
      }
    },

    validateForm() {
      // 验证基本信息
      if (!this.baseInfo.workOrderNo) {
        this.$message.error('请输入工单号');
        return false;
      }
      if (!this.baseInfo.productCode) {
        this.$message.error('请输入产品代码');
        return false;
      }
      if (!this.baseInfo.batchNo) {
        this.$message.error('请输入批次号');
        return false;
      }

      // 验证检验记录
      for (let i = 0; i < this.formRows.length; i++) {
        const row = this.formRows[i];
        if (!row.startDate) {
          this.$message.error(`第${i+1}行检验记录：请选择开始日期`);
          return false;
        }
        if (!row.startTime) {
          this.$message.error(`第${i+1}行检验记录：请选择开始时间`);
          return false;
        }
        if (!row.endDate) {
          this.$message.error(`第${i+1}行检验记录：请选择结束日期`);
          return false;
        }
        if (!row.endTime) {
          this.$message.error(`第${i+1}行检验记录：请选择结束时间`);
          return false;
        }
        if (!row.inspectors || row.inspectors.length === 0) {
          this.$message.error(`第${i+1}行检验记录：请选择检验员`);
          return false;
        }
        if (!row.status) {
          this.$message.error(`第${i+1}行检验记录：请选择状态`);
          return false;
        }
        if (row.quantity === null || row.quantity < 0) {
          this.$message.error(`第${i+1}行检验记录：请输入有效的数量`);
          return false;
        }
        if (!row.totalTime || isNaN(parseFloat(row.totalTime))) {
          this.$message.error(`第${i+1}行检验记录：时间范围异常，请重新选择`);
          return false;
        }
      }
      return true;
    },

    handleDialogClose() {
      this.resetFormData();
      this.dialogVisible = false;
    },

    formatDateTime(date, time) {
      if (!(date instanceof Date) || !(time instanceof Date)) return '';
      const year = date.getFullYear();
      const month = this.padZero(date.getMonth() + 1);
      const day = this.padZero(date.getDate());
      const hours = this.padZero(time.getHours());
      const minutes = this.padZero(time.getMinutes());
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },

    padZero(num) {
      return num < 10 ? `0${num}` : num;
    },

    calculateTimeDiff(row) {
      if (!(row.startDate instanceof Date) || !(row.startTime instanceof Date) ||
          !(row.endDate instanceof Date) || !(row.endTime instanceof Date)) {
        row.totalTime = '';
        return;
      }

      // 组合完整时间
      const startTime = new Date(
        row.startDate.getFullYear(),
        row.startDate.getMonth(),
        row.startDate.getDate(),
        row.startTime.getHours(),
        row.startTime.getMinutes()
      );
      const endTime = new Date(
        row.endDate.getFullYear(),
        row.endDate.getMonth(),
        row.endDate.getDate(),
        row.endTime.getHours(),
        row.endTime.getMinutes()
      );

      if (startTime > endTime) {
        this.$message.warning('开始时间不能晚于结束时间');
        row.totalTime = '';
        return;
      }

      // 计算小时差（保留2位小数）
      const diffMs = endTime - startTime;
      const diffHours = (diffMs / 3600000).toFixed(2);
      row.totalTime = diffHours;
    }
  },
  created() {
    // 1. 获取权限（从store）
    const permissionData = this.$store.getters.getPermission('/suigd') || {};
    this.PermissionAll = permissionData.permission || [];
    console.log("当前用户权限:", this.PermissionAll);

    // 2. 获取用户信息（可选）
    console.log("当前用户信息:", this.$store.getters.getUserInfo() || '未获取到');

    // 3. 初始化数据
    this.get_gx_detail_all();
    console.log("初始化完成");

    // 4. 容错：默认权限（开发环境用，生产环境移除）
    if (this.PermissionAll.length === 0) {
      console.log("未获取到权限，使用默认权限（开发环境）");
      this.PermissionAll = ['Add', 'Update', 'Delete', 'Export'];
    }
  }
};
</script>

<style scoped>
.inspection-form-container {
  padding: 20px;
  background-color: #fff;
  min-height: 500px;
}

.operation-bar {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.dialog-content {
  max-height: 600px;
  overflow-y: auto;
  padding-right: 10px;
}

.dialog-section {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.dialog-section:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.section-title {
  margin-bottom: 15px;
  color: #333;
  font-size: 16px;
  font-weight: 500;
  padding-left: 5px;
  border-left: 3px solid #42b983;
}

.form-group {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 15px;
}

.form-row {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px dashed #e5e5e5;
  flex-wrap: wrap; /* 适配小屏幕 */
}

.form-row:last-child {
  border-bottom: none;
}

.permission-info {
  margin-left: auto;
  color: #666;
  font-size: 12px;
  padding: 5px 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.permission-enabled {
  color: #42b983;
  font-weight: bold;
}

.el-input[readonly] {
  background-color: #f5f7fa;
  color: #666;
}

/* 导出按钮样式协调 */
.el-button--info {
  margin-left: 10px;
}
</style>